/**
 * @description  barra工作台（因子收益贡献）
 * @author swl
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, Spin } from 'antd';
import { XYAxisChartsC, ThreeHeaderC, TableC, SecondHeaderC } from '../../../../../../comps';
import styles from './index.less';

class FactorInfo extends PureComponent {
  // 默认值
  static defaultProps = {};

  constructor() {
    super();
    this.state = {
      columnsStyle: [
        {
          title: '风格因子',
          key: 'factor',
          render: (text, record) => {
            if (text) {
              return <a onClick={() => this.selectRow(record)}>{text}</a>;
            } else {
              return '--';
            }
          },
        },
        {
          title: '平均暴露度',
          key: 'avg_expouse',
        },
        {
          title: '超额收益率贡献',
          key: 'return_contribution',
        },
      ],
      columnsIndustry: [
        {
          title: '行业因子',
          key: 'factor',
          render: (text, record) => {
            if (text) {
              return <a onClick={() => this.selectRow(record)}>{text}</a>;
            } else {
              return '--';
            }
          },
        },
        {
          title: '平均暴露度',
          key: 'avg_expouse',
        },
        {
          title: '超额收益率贡献',
          key: 'return_contribution',
        },
      ],
      dataStyle: [],
      dataIndustry: [],
      dayIncome: {}, //日收益数据
      allIncome: {}, //累计收益数据
    };
  }
  componentDidMount() {
    this.getInfo(this.props.searchData);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.searchData) !== JSON.stringify(this.props.searchData)) {
      this.getInfo(nextProps.searchData);
    }
  }

  // 获取因子变革数据
  getInfo = (searchData) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'incomeAnalysisM/factorContributionDetail',
      payload: searchData,
      callback: (res) => {
        console.log(res);
        this.setState({
          dataStyle: res.data2.dataSource,
          dataIndustry: res.data1.dataSource,
        });
        if (res.data2 && res.data2.dataSource && res.data2.dataSource.length) {
          this.selectRow(res.data2.dataSource[0]);
        }
      },
    });
  };

  // 改变columns的样式
  changeColumns = (columns) => {
    let data = columns;
    if (data && data.length) {
      data.map((item) => {
        if (item.key == 'avg_expouse') {
          item.sorter = (a, b) => a[item.key] - b[item.key];
          item.render = (text) => {
            if (text === null || text === undefined || text === '--') {
              return '--';
            } else {
              return Number(text).toFixed(2);
            }
          };
        }
        if (item.key == 'return_contribution') {
          item.type = 'rate';
          item.sorter = (a, b) => a[item.key] - b[item.key];
        }
      });
    }
    return data;
  };

  // 风格因子
  showStyleTable = () => {
    const { columnsStyle, dataStyle } = this.state;
    const { loading } = this.props;
    let columns = this.changeColumns(columnsStyle);
    return (
      <TableC columns={columns} dataSource={dataStyle} rowKey='id' hidePage={true} scroll={{ y: 200 }} loading={loading.effects['incomeAnalysisM/factorContributionDetail']} />
    );
  };

  // 行业因子
  showIndustryTable = () => {
    const { columnsIndustry, dataIndustry } = this.state;
    const { loading } = this.props;
    let columns = this.changeColumns(columnsIndustry);
    return (
      <TableC columns={columns} dataSource={dataIndustry} scroll={{ y: 200 }} hidePage={true} rowKey='id' loading={loading.effects['incomeAnalysisM/factorContributionDetail']} />
    );
  };

  // 因子点击事件
  selectRow = (record) => {
    const { dispatch, searchData } = this.props;
    dispatch({
      type: 'incomeAnalysisM/factorExposure',
      payload: { ...searchData, name: record.factor },
      callback: (res) => {
        let dayIncome = res.dayIncome;
        let allIncome = res.allIncome;
        dayIncome.series.map((item) => {
          if (item.name.indexOf('超额暴露度') != -1) {
            item.type = 'bar';
          } else {
            item.type = 'line';
          }
        });
        allIncome.series.map((item) => {
          if (item.name.indexOf('超额暴露度') != -1) {
            item.type = 'bar';
          } else {
            item.type = 'line';
          }
        });
        this.setState({
          dayIncome: dayIncome,
          allIncome: allIncome,
        });
      },
    });
  };

  // 收益折柱图
  showCharts = (data) => {
    const { loading } = this.props;
    return (
      <Spin spinning={loading.effects['incomeAnalysisM/factorExposure']}>
        <XYAxisChartsC xAxis={data.xAxis} series={data.series} height={'276px'} yAxisUnit={['单位(%)']} width='100%' />
      </Spin>
    );
  };
  render() {
    const { dayIncome, allIncome } = this.state;

    return (
      <div className={styles.factor}>
        <SecondHeaderC title='因子收益贡献' />

        <Row>
          <Col span={12}>
            <div style={{ marginRight: '10px' }}>
              <ThreeHeaderC title={`风格因子`} />
              {this.showStyleTable()}
            </div>
          </Col>
          <Col span={12}>
            <div style={{ marginLeft: '10px' }}>
              <ThreeHeaderC title='行业因子 ' />
              {this.showIndustryTable()}
            </div>
          </Col>
        </Row>
        {/* <div className={styles.tip}>
          *点击某因子，下方展示该因子的收益趋势图
        </div>
        <Row>
          <Col span={12}>
            <div style={{ marginRight: '10px' }}>
              <ThreeHeaderC title={`日收益`} Right={<div className={styles.info}>BETA因子</div>} />
              <div style={{}}>
                {this.showCharts(dayIncome)}
              </div>
            </div>
          </Col>
          <Col span={12}>
            <div style={{ marginLeft: '10px' }}>
              <ThreeHeaderC title='累计收益' Right={<div className={styles.info}>BETA因子</div>} />
              <div style={{}}>
                {this.showCharts(allIncome)}
              </div>
            </div>
          </Col>
        </Row> */}
      </div>
    );
  }
}
export default connect(({ incomeAnalysisM, loading }) => ({
  incomeAnalysisM,
  loading,
}))(FactorInfo);
